package com.bw.user_module.user;

import androidx.room.Room;

import com.bw.base_application_sdk.BaseApplication;
import com.bw.common.mvvm.model.BaseRespository;
import com.bw.network_sdk.BaseEntity;
import com.bw.user_module.dao.UserDatabase;

import java.util.List;

import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

public class UserRespository extends BaseRespository {

    public Observable<BaseEntity> queryUser(){
        UserDatabase db = Room.databaseBuilder(BaseApplication.getInstance(),
                UserDatabase.class, "user.db").build();
        Maybe<List<UserValueEntity>> maybe = db.userDao().queryUser();
        Observable<BaseEntity>userValueEntityObservable = maybe.flatMapObservable(
                new Function<List<UserValueEntity>, ObservableSource<? extends BaseEntity>>() {
                    @Override
                    public ObservableSource<? extends BaseEntity> apply(
                            @NonNull List<UserValueEntity> userValueEntities) throws Exception {
                        UserEntity entity = new UserEntity();
                        entity.status = 200;
                        if (userValueEntities == null){
                            entity.message="用户未登录";
                            Observable<UserEntity>userEntityObservable = Observable.just(entity);
                            return functionObservable(userEntityObservable);
                        }
                        if (userValueEntities.size() == 0){
                            entity.message="用户未登录";
                            Observable<UserEntity>userEntityObservable = Observable.just(entity);
                            return functionObservable(userEntityObservable);
                        }
                        entity.message="用户已登录";
                        entity.data = userValueEntities.get(userValueEntities.size()-1);
                        Observable<UserEntity>userEntityObservable = Observable.just(entity);
                        return functionObservable(userEntityObservable);
                    }
                }
        );
        return userValueEntityObservable;
    }

}
